package com.reggie.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reggie.common.R;
import com.reggie.dto.DishDto;
import com.reggie.dto.SetmealDto;
import com.reggie.entity.Category;
import com.reggie.entity.Dish;
import com.reggie.entity.Setmeal;
import com.reggie.entity.SetmealDish;
import com.reggie.service.CategoryService;
import com.reggie.service.DishService;
import com.reggie.service.SetmealDishService;
import com.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐(Setmeal)表控制层
 *
 * @author makejava
 * @since 2022-09-01 18:39:15
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {
    /**
     * 服务对象
     */
    @Resource
    private SetmealService setmealService;

    @Resource
    private SetmealDishService setmealDishService;

    @Resource
    private CategoryService categoryService;

    @Resource
    private DishService dishService;

    @PostMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R save(@RequestBody SetmealDto setmealDto) {
        log.info("保存套餐：{}", setmealDto);
        setmealService.saveWithDish(setmealDto);
        return R.success(null);
    }

    /**
     * 套餐分页查询
     *
     * @param page     当前页码
     * @param pageSize 每页数据量
     * @param queryKey 查询关键字
     * @return 查询页面数据
     */
    @GetMapping("/page")
    public R<Page> page(@RequestParam("page") int page, @RequestParam("pageSize") int pageSize, @RequestParam(name = "name", required = false) String queryKey) {
        // 分页构造器
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Setmeal> queryWrapper = Wrappers.lambdaQuery(Setmeal.class);
        queryWrapper.like(StrUtil.isNotEmpty(queryKey), Setmeal::getName, queryKey)
                .orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(pageInfo, queryWrapper);
        List<Setmeal> setmealList = pageInfo.getRecords();
        List<SetmealDto> setmealDtoList = setmealList.stream()
                .map(setmeal -> {
                    SetmealDto setmealDto = new SetmealDto();
                    BeanUtil.copyProperties(setmeal, setmealDto);
                    Category category = categoryService.getById(setmeal.getCategoryId());
                    setmealDto.setCategoryName(category.getName());
                    // 这个条目可以不用复制，我是写着练手玩~
                    List<SetmealDish> setmealDishes = setmealDishService.list(
                            Wrappers.lambdaQuery(SetmealDish.class).eq(SetmealDish::getSetmealId, setmeal.getId())
                    );
                    setmealDto.setSetmealDishes(setmealDishes);
                    return setmealDto;
                }).collect(Collectors.toList());
        Page<SetmealDto> realPageInfo = new Page<>();
        BeanUtil.copyProperties(pageInfo, realPageInfo, "records");
        realPageInfo.setRecords(setmealDtoList);
        return R.success(realPageInfo);
    }

    /**
     * 停售起售
     *
     * @param status 状态码
     * @param ids    需要更改的套餐
     * @return 修改结果
     */
    @PostMapping("/status/{status}")
    public R updateStatus(@PathVariable("status") int status, Long... ids) {
        log.info("修改目标：{}", status == 0 ? "停售" : "起售");
        setmealService.updateBatchById(setmealService.listByIds(Arrays.asList(ids))
                .stream()
                .peek(dish -> dish.setStatus(status))
                .collect(Collectors.toList()));
        return R.success(null);
    }

    /**
     * 删除套餐
     *
     * @param ids 删除id
     * @return 是否成功
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R delete(@RequestParam("ids") List<Long> ids) {
        setmealService.removeWithDishes(ids);
        return R.success(null);
    }

    /**
     * 根据条件查询对应的套餐数据
     *
     * @param setmeal 查询条件
     * @return 套餐列表
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache", key = "#setmeal.categoryId + ':' + #setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        LambdaQueryWrapper<Setmeal> queryWrapper = Wrappers.lambdaQuery(Setmeal.class);
        queryWrapper.eq(StrUtil.isNotBlank(setmeal.getCategoryId().toString()), Setmeal::getCategoryId, setmeal.getCategoryId())
                .eq(Setmeal::getStatus, 1)
                .orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> setmealList = setmealService.list(queryWrapper);
        return R.success(setmealList);
    }

    /**
     * 回显套餐数据：根据套餐id查询套餐
     *
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> getData(@PathVariable Long id) {
        SetmealDto setmealDto = setmealService.getDate(id);
        return R.success(setmealDto);
    }

    @PutMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R<String> update(@RequestBody SetmealDto setmealDto) {

        if (setmealDto == null) {
            return R.error("请求异常");
        }

        if (setmealDto.getSetmealDishes() == null) {
            return R.error("套餐没有菜品,请添加套餐");
        }

        Long setmealId = setmealDto.getId();
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, setmealId);
        setmealDishService.remove(queryWrapper);

        //为setmeal_dish表填充相关的属性
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes().stream().peek(setmealDish -> {
            setmealDish.setSetmealId(String.valueOf(setmealId));
        }).collect(Collectors.toList());

        //批量把setmealDish保存到setmeal_dish表
        setmealDishService.saveBatch(setmealDishes);
        setmealService.updateById(setmealDto);

        return R.success("套餐修改成功");
    }


    /**
     * 移动端点击套餐图片查看套餐具体内容
     * 这里返回的是dto 对象，因为前端需要copies这个属性
     * 前端主要要展示的信息是:套餐中菜品的基本信息，图片，菜品描述，以及菜品的份数
     *
     * @param SetmealId
     * @return
     */
    //这里前端是使用路径来传值的，要注意，不然你前端的请求都接收不到，就有点尴尬哈
    @GetMapping("/dish/{id}")
    public R<List<DishDto>> dish(@PathVariable("id") Long SetmealId) {
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, SetmealId);
        //获取套餐里面的所有菜品  这个就是SetmealDish表里面的数据
        List<SetmealDish> setmealDishList = setmealDishService.list(queryWrapper);

        List<DishDto> dishDtos = setmealDishList.stream().map((setmealDish) -> {
            DishDto dishDto = new DishDto();
            //其实这个BeanUtils的拷贝是浅拷贝，这里要注意一下
            BeanUtils.copyProperties(setmealDish, dishDto);
            //这里是为了把套餐中的菜品的基本信息填充到dto中，比如菜品描述，菜品图片等菜品的基本信息
            Long dishId = Long.valueOf(setmealDish.getDishId());
            Dish dish = dishService.getById(dishId);
            BeanUtils.copyProperties(dish, dishDto);
            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtos);
    }
}

